import Koa from 'koa'
import KoaBody from 'koa-body'
import KoaLogger from 'koa-logger'
import log, { trace } from './config/logger'
import { server } from './config'
import { executeServiceInterface } from './service'
import { checkUserToken } from './service/impl/AuthService'

const port = server.port
const app = new Koa()

app.use(KoaLogger({
  transporter: (str, args) => {
    trace.trace(str)
  }
}))

app.use(KoaBody())

app
  .use(async (ctx, next) => {
    try {
      await next()
    } catch (error) {
      ctx.status = error.status || 500
      const err = {
        ...error,
        code: error.status || 500
      }
      ctx.body = err
      log.info(JSON.stringify(err))
    }
  })
  .use(async (ctx, next) => {
    const fullServiceNo: string = ctx.header.service
    const token = ctx.header.authorization
    await checkUserToken(ctx, fullServiceNo, token)
    await executeServiceInterface(ctx, fullServiceNo || '')
    await next()
  })

app.listen(port, () => {
  log.info(`server running on localhost:${port}`)
})
